package com.wbk.lotterysystemlotteryservice.service.serviceImpl;

import com.wbk.lotterysystemlotteryservice.entity.QrCode;
import com.wbk.lotterysystemlotteryservice.entity.QrCodeExample;
import com.wbk.lotterysystemlotteryservice.mapper.QrCodeMapper;
import com.wbk.lotterysystemlotteryservice.service.QrCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class QrCodeServiceImpl implements QrCodeService {

    @Autowired
    QrCodeMapper qrCodeMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public QrCode save(Integer lotteryId, String url) {
        QrCode qrCode = new QrCode();
        qrCode.setLotteryId(lotteryId);
        qrCode.setQrCode(url);
        qrCodeMapper.insertSelective(qrCode);
        return qrCode;
    }

    @Cacheable(cacheNames = "qrCode::byLotteryId", key = "#lotteryId")
    @Override
    public QrCode getQrCodeByLotteryId(Integer lotteryId) {
        QrCodeExample qrCodeExample = new QrCodeExample();
        QrCodeExample.Criteria criteria = qrCodeExample.createCriteria();
        criteria.andLotteryIdEqualTo(lotteryId);
        List<QrCode> qrCodes = qrCodeMapper.selectByExample(qrCodeExample);
        if (qrCodes.isEmpty()) {
            return null;
        }
        return qrCodes.get(0);
    }
}
